import jianghuService from '../../service/jianghu.service'
import config from '../../config'
import pkService from '../../service/pk.service'
const app = getApp()

Page({

  data: {
    tabs: [ // 一级tab
      {title: '琅琊榜'},
      {title: '积分榜'}
    ],
    subTabs: [ // 二级tab
      {title: '竞技'},
      {title: '传统弓'},
      {title: '美猎/光弓'}
    ],
    activeTab: 0, // 一级tab获焦索引
    subActiveTab: 0, // 二级tab获焦索引
    scoreRankData: [], // 积分排行数据
    fanQuRankData: [], // 反曲排行数据
    chuanTongRankData: [], // 传统弓排行数据
    meiLieRankData: [], // 美猎排行数据
    subFanQuRankData: [], // 反曲排行数据-未认证
    subChuanTongRankData: [], // 传统弓排行数据-未认证
    subMeiLieRankData: [], // 美猎排行数据-未认证
    // scrollTop: 0,
    pageNo: 1, // 用户积分排行页码
    pageSize: 10, // 用户积分排行条目
    subPageNo: 1, // 用户未认证打榜页码
    subPageSize: 10, // 用户未认证打榜条目
    targetId:'',//PK 对象用户id
    pkScore: '', //PK积分
    studentPKData:[],
    animationInfo: {}, // 动画信息
    animationStatus: false, // 默认不全显示
    animationCloseTime: null,
    userRankInfoModal: false, // 用户设置打榜信息弹窗
    items: [
      { name: '竞技', value: '0', checked: false },
      { name: '传统弓', value: '1', checked: false },
      { name:'美猎/光弓', value: '2', checked: false },
    ],
    // userScore: '', // 用户打榜积分
    userScoreType: '', // 用户打榜积分类型
    modalTitle: '', // modal主标题
    modalSubTitle: '', // modal副标题
    modalOpened: false, // modal是否打开
    modalCallback: null, // modal确认点击按钮回调事件
    modalBtnTextArr: [ // 定义modal按钮文案
      { text: '取消' },
      { text: '确认'}
    ],
    qrcodeImg: '', // 认证二维码
    qrcodeMaskOpened: false ,// 认证二维码弹窗
    pkModal:false,
    pkScore:0
  }, 

  onLoad(options) { // 通过个人中心 积分窗口访问页面
    if (options.type) {
      this.setData({
        activeTab: 1
      })
      this.getScoreRankData()
    } 

    else { // 正常通过tabbar访问页面
      this.getLangYaRank(0)
      this.userRankList(0)
    }
    // this.getPageData({
    //   index: Number(options.value),
    //   tabsName: options.type ? options.type : 'activeTab'
    // }, {
    //   isFristOpenPage: true,
    //   loadWith: 'load'
    // })
  },
  iptPkScore(e) {
    this.setData({
      pkScore: e.detail.value
    })
  },
  checkPkScore(e) {
    if(e.detail.value < 10){
         this.openModal({
          title: '提示',
          subtitle: 'pk 最低也要10个积分',
          cb: function () {
            that.addPkModal()
          }
        })
    }
  },

  onShow() {
     var animation = dd.createAnimation({
      duration: 200,
      timeFunction: 'linear',
    });
    this.animation = animation;
    this.animation.left(-25).step();
    this.setData({
      animationInfo: this.animation.export()
    });
    this.setData({
      animationStatus: false
    })
  },

  // tab点击切换事件， 获取数据
  // getPageData({ index, tabsName }, options) {
  //   let that = this
  //   let isFristOpenPage = false
  //   let loadWith = 'load'

  //   if (options && options.isFristOpenPage) {
  //     isFristOpenPage = true
  //   }

  //   if (options && options.loadWith == 'next') {
  //     loadWith = 'next'
  //   }

  //   if (tabsName == 'activeTab') { // 积分榜
  //     if (that.data.activeTab == index && 
  //       !isFristOpenPage && loadWith != 'next') { // 一级tab 点击自身, 不需要改变
  //         return 
  //     } else {
  //         if (loadWith == 'load') {
  //         that.setData({
  //         [tabsName]: index,
  //         pageNo: 1,
  //         // scrollTop: 0
  //         });
  //       } else if (loadWith == 'next'){
  //         that.data.pageNo = that.data.pageNo + 1
  //         console.log(that.data.pageNo)
  //       }
  //     }
  //   }
    

  //   if (tabsName == 'subActiveTab') { // 琅琊榜
  //       if (that.data.subActiveTab == index && 
  //       !isFristOpenPage && loadWith != 'next') { // 二级tab 点击自身, 不需要改变
  //       return 
  //     } else {
  //       if (loadWith == 'load') {
  //         that.setData({
  //           [tabsName]: index,
  //           pageNo: 1,
  //           // scrollTop: 0
  //         });
  //       } else if (loadWith == 'next'){
  //         that.data.pageNo += 1
  //       }
  //     }
  //   }
    

  //   if (tabsName == 'activeTab') {
  //     if (index == 0) { // 展示琅琊榜
  //       console.log('展示琅琊榜')
  //     } else if (index == 1) { // 展示积分榜
  //       that.getScoreRankData(loadWith)
  //     } 

  //   } else { // 二级tab
      
  //     if (index == 0) { // 展示反曲排行榜
  //       console.log('展示反曲排行榜')
  //       that.getLangYaRank(0)
  //     } else if (index == 1) { // 展示传统弓箭排行榜
  //       console.log('展示传统弓箭排行榜')
  //       that.getLangYaRank(1)
  //     } else if (index == 2) { // 展示美猎排行榜
  //       console.log('展示美猎排行榜')
  //       that.getLangYaRank(2)
  //     }

  //   }
  // },
  // 一级tab切换事件
  changeTab({index}) { // index-当前获焦tab下标；
    console.log(index)
    if (this.data.activeTab == index) { // 点击自身
      return
    }
    this.setData({
      pageNo: 1,
      activeTab: index
    })

    if (index == 1) {
      this.getScoreRankData()
      this.studentPkList()
    } 
    else {
      this.getLangYaRank(0) 
      this.userRankList(0)     
    }
  },

  // 二级tab切换事件
  changeSubTab({index}) { // index-当前获焦tab下标；tabsName
    if (this.data.subActiveTab == index) { // 点击自身
      return
    }
    console.log(index)
    this.setData({
      pageNo: 1,
      subActiveTab: index
    })
    this.getLangYaRank(index)      
    this.userRankList(index)     
  },
 
  // 获取积分排行数据
  getScoreRankData () {
    let that = this
    let params = {
      pageNo: that.data.pageNo,
      pageSize: that.data.pageSize
    }

    let success = function (res) {
      let data = res.data.result.datas
      if (data && data.length > 0) {
        if (that.data.pageNo == 1) {
          that.setData({
            scoreRankData: data
          })
        } else {
          that.setData({
            scoreRankData: that.data.scoreRankData.concat(data)
          })
        }
      } else {
        if (that.data.pageNo > 1) {
          that.data.pageNo = that.data.pageNo - 1
          dd.showToast({
            type: 'none',
            content: '暂无更多数据'
          })
        }
      }
    } 

    let fail = function (msg) {
      if (this.data.pageNo > 1) {
        this.data.pageNo = this.data.pageNo - 1
      }
      dd.showToast({
        type: 'fail',
        content: msg
      })
    }

    jianghuService.getScoreRankNumber(params, success, fail)
  },

  // 获取琅琊榜排行数据
  getLangYaRank(type) {
    let that = this
    let params = {
      pageNo: that.data.pageNo,
      pageSize: that.data.pageSize,
      type: type
    }

    let success = function (res) {
      let data = res.data.result.datas
      if (data && data.length > 0) {
        if (that.data.pageNo == 1) {
          if (type == 0) {
            that.setData({
              fanQuRankData: data
            })
          }
          if (type == 1) {
            that.setData({
              chuanTongRankData: data
            })
          }

          if (type == 2) {
            that.setData({
              meiLieRankData: data
            })
          }
        } 
        else {
          if (type == 0) {
            that.setData({
              fanQuRankData: that.data.fanQuRankData.concat(data)
            })
          }

          if (type == 1) {
            that.setData({
              chuanTongRankData: that.data.chuanTongRankData.concat(data)
            })
          }

          if (type == 2) {
            that.setData({
              meiLieRankData: that.data.meiLieRankData.concat(data)
            })
          }
        }
      } else {
        if (that.data.pageNo > 1) {
          that.data.pageNo = that.data.pageNo - 1
          dd.showToast({
            type: 'none',
            content: '暂无更多数据'
          })
        }
      }
    } 

    let fail = function (msg) {
      if (this.data.pageNo > 1) {
        this.data.pageNo = this.data.pageNo - 1
      }
      dd.showToast({
        type: 'fail',
        content: msg
      })
    }

    console.log(params);
    jianghuService.getLangYaRank(params, success, fail)
  },

  // 获取用户未认证数据
  userRankList (type) {
     let that = this
     let params = {
      status: 0,
      studentUid: app.globalData.userInfo.id,
      pageNo: that.data.subPageNo,
      pageSize: that.data.subPageSize,
      type: type
     }

    let success = function (res) {
      console.log('userRankList', res)
      let data = res.data.result
      if (data && data.length > 0) {
          if (type == 0) {
            that.setData({
              subFanQuRankData: data
            })
          }
          if (type == 1) {
            that.setData({
              subChuanTongRankData: data
            })
          }

          if (type == 2) {
            that.setData({
              subMeiLieRankData: data
            })
          }
      } else {
        if (type == 0) {
            that.setData({
              subFanQuRankData: []
            })
          }
          if (type == 1) {
            that.setData({
              subChuanTongRankData: []
            })
          }

          if (type == 2) {
            that.setData({
              subMeiLieRankData: []
            })
          }
      }
    } 

    let fail = function (msg) {
      dd.showToast({
        type: 'fail',
        content: msg
      })
    }

    console.log(params);
    jianghuService.userRankList(params, success, fail)
  },

  // 添加打榜数据
  addUserRank() {
    let that = this
    let params = {
      // sort: this.data.userScore,
      studentUid: app.globalData.userInfo.id,
      type: this.data.userScoreType
    }

    let success = function (res) {
       if (res.data && res.data.code == 0) {
        dd.showToast({
          type: 'success',
          content: '打榜信息申请成功'
        })
        that.closeUserRankInfoModal()
        that.getLangYaRank(that.data.subActiveTab)
        that.userRankList(that.data.subActiveTab)
       }
    }

    let fail = function (msg) {
      dd.showToast({
        type: 'fail',
        content: msg
      })
    }

    console.log('addUserRank', params)
    jianghuService.addUserRank(params, success, fail)
  },

  // 获取认证二维码
  confirmRankInfo(e) {
    let that = this
    that.setData({
        qrcodeImg: config.domain + '/ranking/getCode?' + 'id=' + e.target.dataset.id,
        qrcodeMaskOpened: true
    })
  },

  // 删除打榜数据
  deleteRankInfo(e) {
    let that = this
    let id = e.target.dataset.id
    let params = {
      id: id
    }

    let success = function (res) {
      console.log('deleteRankInfo', res)
      if (res.data && res.data.code == 0) {
        dd.showToast({
          type: 'success',
          content: '删除成功'
        })
        that.userRankList(that.data.subActiveTab)
      }
    }

    let fail = function (msg) {
      dd.showToast({
        type: 'fail',
        content: msg
      })
    }

    this.openModal({
      title: '提示',
      subtitle: '您确定要删除此条打榜信息？',
      cb: function () {
        jianghuService.deleteUserRank(params, success, fail)
      }
    })
  },

  onScrollToLower (e) {
    this.data.pageNo += 1
    if (e.target.dataset.type == 'activeTab1') {
      this.getScoreRankData()
    } 
    if (e.target.dataset.type == 'subActiveTab0') {
      this.getLangYaRank(0)
      this.userRankList(0)     

    } 
    if (e.target.dataset.type == 'subActiveTab1') {
      this.getLangYaRank(1) 
      this.userRankList(1)     

    } 
    if (e.target.dataset.type == 'subActiveTab2') {
      this.getLangYaRank(2)    
      this.userRankList(2)     
    } 
  },
  // 点击页面body隐藏左侧悬浮按钮
  closeLeftBtn () {
    let that = this
    that.animation.left(-25).step();
    that.setData({
      animationInfo: that.animation.export()
    });
    that.setData({
      animationStatus: false
    })
    that.data.animationCloseTime = null
  },
  // 关闭认证二维码弹窗
  qrcodeMaskClose() {
    this.setData({
      qrcodeMaskOpened: false
    })
    this.userRankList(this.data.subActiveTab)
  },
  // 监听悬浮按钮是否显示, 3秒回还显示则关闭
  setAnimatTime() {
    let that = this
    return setTimeout(()=> {
      if (that.data.animationStatus) { // 3秒后还是打开状态就关闭
         that.animation.left(-25).step();
          that.setData({
            animationInfo: that.animation.export()
          });
          that.setData({
            animationStatus: false
          })
          that.data.animationCloseTime = null
      }
    }, 3000)
  },
  // 显示打榜信息弹窗
  showModal() {
    this.data.items[0]['checked'] = false
    this.data.items[1]['checked'] = false
    this.data.items[2]['checked'] = false
    this.setData({
      items: this.data.items,
      userScoreType: '',
      // userScore: '',
      userRankInfoModal: true
    })
  },
  updatePkResult(e){
    let that = this
      let params = {
        tenantId: 1,
        refereeId: app.globalData.userInfo.id, 
        id: e.target.dataset.id,
        result: e.target.dataset.result
      }

      let success = function (res) {
         dd.showToast({
          type: 'success',
          content: 'PK处理成功'
        })
        that.studentPkList();
        that.getScoreRankData();
      } 

      let fail = function (msg) {
        dd.showToast({
          type: 'fail',
          content: msg
        })
        that.studentPkList();
        that.getScoreRankData();
      }
      pkService.updatePkResult(params, success, fail)
  },
  actionPK(e) {
   let that = this
    let params = {
      targetId: that.data.targetId,
      type:"弓箭积分PK",
      sourceId:app.globalData.userInfo.id,
      tenantId:1,
      integral: that.data.pkScore
    }
    this.openModal({
      title: '确认发起本次pk吗?',
      subtitle: '将会冻结双方的积分直到分出胜负或者对方拒绝,每天只能发起一次pk和被挑战一次的pk。',
      cb: function () {
          let success = function (res) {
            console.log('pkAction', res)
            if (res.data && res.data.code == 0) {
              dd.showToast({
                type: 'success',
                content: '发起PK 成功'
              })
              that.getScoreRankData()
            }
          }

          let fail = function (msg) {
            dd.showToast({
              type: 'fail',
              content: msg
            })
          }
          jianghuService.addPK(params ,success, fail)
     }
    })
  },
   // 获取用户未认证数据
  studentPkList () {
     let that = this
     //获取未处理的pk 数据
     console.log("------1")
    if(app.globalData.userInfo.role >= 4){
      let params = {
        id:app.globalData.userInfo.id,
        tenantId: 1,
        status: "已接受",
        result: "未处理"
      }
     console.log("------ 2")
      let success = function (res) {
        let data = res.data.result
        if (data && data.length > 0) {
              that.setData({
                studentPKData: data
              })
        }else{
            that.setData({
                studentPKData: []
            })
        }
      } 
     console.log("------ 3")
      let fail = function (msg) {
        dd.showToast({
          type: 'fail',
          content: msg
        })
      }
      pkService.studentPkList(params, success, fail)
    }

  },
  openPkModal(e){
    this.setData({
      pkScore: 0,
      pkModal: true,
      targetId: e.target.dataset.id,
    })
  },

  closePkModal(){
     this.setData({
      pkModal: false
    })
  },
  
  // 切换悬浮打榜按钮
  animationChange () {
    if (app.methods.enableButtonClicked()) {
      if (!this.data.animationStatus) {
        this.animation.left(0).step();
        this.setData({
          animationInfo: this.animation.export()
        });
        this.setData({
          animationStatus: true
        })
        this.data.animationCloseTime = this.setAnimatTime() // 计算3秒时间, 3秒后关闭
      } else {
        clearInterval(this.data.animationCloseTime) // 清楚定时器
        this.data.animationCloseTime = null // 重置变量
        this.data.animationCloseTime = this.setAnimatTime() // 重新计算3秒时间
        this.showModal()
      }
    }
  },
  // 关闭设置打榜信息弹窗
  closeUserRankInfoModal() {
    this.setData({
      userRankInfoModal: false
    })
  },

  // 用户选择打榜类型
  radioChange(e) {
    this.data.items[e.detail.value]['checked'] = true
    this.setData({
      userScoreType: e.detail.value,
      items: this.data.items
    })
  },
  // 用户输入打榜积分
  // iptEnterUserScore(e) {
  //   this.setData({
  //     userScore: e.detail.value
  //   })
  // },

  /**
   * 打开modal
   */
  openModal(opts) {
    this.setData({
      modalBtnTextArr: [
        {
          text: opts.ltext || '取消'
        },
        {
          text: opts.rtext || '确定'
        }
      ],
      modalTitle: opts.title || '',
      modalSubTitle: opts.subtitle || '',
      modalOpened: true,
      modalCallback: opts.cb || ''
    })
  },

   /**
   * modal框按钮点击回调
   */
  modalButtonClick(e) {
    let type = e.target.dataset.index
    if (type == 0) { // 关闭modal
      this.setData({
        modalOpened: false
      })
    } else {
      if (this.data.modalCallback && typeof this.data.modalCallback === 'function') {
        this.setData({
          modalOpened: false
        })
        this.data.modalCallback()
      }
    }
  },

  // 确认提交打榜信息
  confirmRank() {
    let that = this
    if (!this.data.userScoreType) {
       dd.showToast({
        type: 'fail',
        content: '请选择打榜类型'
       })
      return 
    } 

    // if (this.data.userScore) {
    //    let reg = /(^[1-9]\d*$)/;
    //    if  (!reg.test(this.data.userScore)) {
    //       dd.showToast({
    //         type: 'fail',
    //         content: '不合理的分数值,分数范围为1-120的正整数1'
    //       })
    //       return 
    //    } else {
    //      if (this.data.userScore <= 0 || this.data.userScore > 120) {
    //         dd.showToast({
    //         type: 'fail',
    //         content: '不合理的分数值,分数范围为1-120的正整数'
    //       })
    //       return
    //      }
    //    }
    // } else {
    //   dd.showToast({
    //     type: 'fail',
    //     content: '请输入打榜分数'
    //    })
    //   return 
    // }
    
    this.openModal({
      title: '提示',
      subtitle: '您将发起打榜申请，请确认打榜信息输入无误，认证通过后会扣除您50个积分',
      cb: function () {
        that.addUserRank()
      }
    })
  }
})

